<template>
  <el-dialog v-model="visible" :title="title" width="500px" destroy-on-close @close="emit('close')">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="部门名称" prop="FName">
        <el-input v-model="formData.FName" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="上级部门" prop="FParentId">
        <el-select
          v-model="formData.FParentId"
          placeholder="请选择上级部门"
          filterable
          clearable
          style="width: 100%"
          :disabled="!!formData.id"
        >
          <el-option
            v-for="dept in departmentList"
            :key="dept.id"
            :label="dept.FName"
            :value="dept.id"
            :disabled="dept.id === formData.id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { createDepartmentApi, updateDepartmentApi, getDepartmentTreeApi } from "@/api/modules/department";
import { Department } from "@/api/interface/department";

// 定义父组件事件
const emit = defineEmits(["refresh", "close"]);

const visible = ref(false);
const formRef = ref<FormInstance>();
const title = ref("新增部门");
const departmentList = ref<Department.DepartmentItem[]>([]);

const formData = reactive({
  id: "",
  FName: "",
  FParentId: undefined as string | undefined
});

const rules = reactive<FormRules>({
  FName: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
  FParentId: [{ required: false }]
});

// 加载部门树形数据
const loadDepartments = async () => {
  const { data } = await getDepartmentTreeApi();
  departmentList.value = flattenDepartmentTree(data);
};

// 将树形结构扁平化
const flattenDepartmentTree = (tree: any[], result: any[] = []) => {
  tree.forEach(item => {
    result.push({
      id: item.id,
      FName: item.FName,
      FParentId: item.FParentId
    });
    if (item.children && item.children.length > 0) {
      flattenDepartmentTree(item.children, result);
    }
  });
  return result;
};

// 打开弹窗
const open = (row?: any) => {
  title.value = row?.id ? "编辑部门" : "新增部门";
  if (row?.id) {
    Object.assign(formData, {
      id: row.id,
      FName: row.FName,
      FParentId: row.FParentId || undefined // 将 null 转换为 undefined
    });
  } else {
    resetForm();
  }
  visible.value = true;
};

// 重置表单
const resetForm = () => {
  formData.id = "";
  formData.FName = "";
  formData.FParentId = undefined;
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    const params = {
      FName: formData.FName,
      FParentId: formData.FParentId || null // 将 undefined 转换为 null 用于后端
    };

    if (formData.id) {
      await updateDepartmentApi({
        id: formData.id,
        ...params
      });
      ElMessage.success("更新成功");
    } else {
      await createDepartmentApi(params);
      ElMessage.success("创建成功");
    }

    visible.value = false;
    emit("refresh");
  } catch {
    // 验证失败不处理
  }
};

// 加载部门数据
onMounted(() => {
  loadDepartments();
});

defineExpose({ open });
</script>
